﻿$(function () {
    $('#CheckOut')
        .CreateController({
            appEvents: {
                'bind:order': 'bind',
                'position:submit': 'position',
                'createOrder:submit': 'createOrder'
            },
            events: {
                '#createOrder click': 'createOrder',
                '#OrderXiaModify click': 'TopToModifyAddress',
                '#ComfirmOk click': 'GiftUsedOk',
                '#ComfirmCancel click': 'GiftUsedCancel',
                '#GiftWorningClose click': 'GiftUsedCancel',
                '#SubmitPayPassword click': 'SubmitPayPassword'
            },
            bind: function () {
                 
                this.tmpl({
                    dom: this.OrderViews,
                    v: BENLAI.Model.OrderTemp.OrderTemps,
                    datas: BENLAI.Model.OrderModels
                });
                BENLAI.Shop.Orders.Address();
                BENLAI.Shop.Invoice.Invoice();
                BENLAI.Shop.Orders.Pay();
                BENLAI.Shop.Orders.Package();
                BENLAI.Shop.Orders.ProductList();
                BENLAI.Model.OrderTemp.UpdateOrder = false;
                BENLAI.Model.OrderTemp.UpdatePayMethod = false;
                if (BENLAI.Model.OrderTemp.z1) {
                    $('[data-addid="AddressList2"]').show();
                    $("#moreaddr").html("收回其他地址");
                    $("#moreaddr").attr("status", "2");
                }
                var num = -1;
                $('[data-id="CouponInfoList"] [type="radio"]')
                    .each(function (k, v) {
                        if ($(v).attr("checked"))
                            num = $(v).parent().parent().attr("data-couponfenid");
                    });
                if (num != -1 && num != 1) {
                    BENLAI.Shop.Orders.FenPage(num, 1);
                }
                 
                //if (BENLAI.Model.OrderTemp.PackageTimeSelect > 0) {
                //    if ($('[data-type="sendtimeselect"][data-shipid="' +
                //            BENLAI.Model.OrderTemp
                //            .PackageTimeSelect +
                //            '"]')
                //        .length) {
                //        var html = $('[data-type="sendtimeselect"][data-shipid="' +
                //                BENLAI.Model.OrderTemp.PackageTimeSelect +
                //                '"]')
                //            .html();
                //        $('[data-type="sendtime"]').html(html);
                //        $('[data-type="sendtime"]').attr("data-shipid", BENLAI.Model.OrderTemp.PackageTimeSelect);
                //        $('[data-type="sendtime"]')
                //            .parents("tr")
                //            .find("[data-id='pfdrd']")
                //            .html($('[data-type="sendtimeselect"][data-shipid="' +
                //                    BENLAI.Model.OrderTemp.PackageTimeSelect +
                //                    '"]')
                //                .attr("data-remark"));
                //    }
                //}
                if (BENLAI.Model.OrderTemp.PayType) {
                    var IsPayTypeCheck = false;
                    $("[name=PayType]")
                        .each(function (k, v) {
                            if ($(v).val() == BENLAI.Model.OrderTemp.PayType) {
                                $(v).attr("checked", true);
                                IsPayTypeCheck = true;
                            } else {
                                $(v).attr("checked", false);
                            }
                        });
                    if (!IsPayTypeCheck) {
                        $("[name=PayType]").eq(0).attr("checked", true);
                        BENLAI.Model.OrderTemp.PayType = $("[name=PayType]").eq(0).val();
                    }
                }
                if (BENLAI.Model.OrderTemp.CouponShow || Number(BENLAI.Model.OrderModels.IsUseConpon) === 1) {
                    $("#UseCouponCB").attr("checked", true);
                    $('[data-type="CouponShow"]').show();
                    $.App.trigger("position:submit");
                } else {
                    $("#UseCouponCB").attr("checked", false);
                    $('[data-type="CouponShow"]').hide();
                    $.App.trigger("position:submit");
                }


                if (BENLAI.Model.OrderTemp.Print) {
                    $("[name=printmoney]")
                        .each(function (k, v) {
                            if ($(v).val() == BENLAI.Model.OrderTemp.Print) {
                                $(v).attr("checked", true);
                            } else {
                                $(v).attr("checked", false);
                            }
                        });
                }
                if (BENLAI.Model.OrderModels.NoStoreMsg != "" &&
                    !BENLAI.Model.OrderTemp.hasAlerted &&
                    BENLAI.Model.OrderModels.CustSeletAddr!=null &&
                    BENLAI.Model.OrderModels.CustSeletAddr.DistrictSysNo > 0) {
                    BENLAI.Model.OrderTemp.hasAlerted = true;
                    alert(BENLAI.Model.OrderModels.NoStoreMsg);
                }
                if (BENLAI.Model.OrderModels.TotalNeedPay > 0) {
                    $("#invoiceUl input[name='invoiceType']").removeAttr("disabled");
                } else {
                    $("#invoiceUl input[name='invoiceType']").first().click();
                    $("#invoice_title").hide();
                    $("#invoice_paper").hide();
                    $("#invoiceUl input[name='invoiceType']").attr("disabled", "disabled");
                }
            },
            TopToModifyAddress: function (t, event) {
                smoothScroll($("body").offset().top);
            },
            createOrder: function () {
                if (this.createOrder.checkValidate.call(this, arguments)) {
                    var that = this;
                    //判断是否使用余额或礼金卡
                    if (BENLAI.Model.OrderModels.UsedYuE > 0 || BENLAI.Model.OrderModels.UsedGiftCard > 0) {
                        $.ajax({
                            type: "POST",
                            url: "/UserHome/IsSetPayPwd",
                            cache: false,
                            success: function (data) {
                                if (AjaxValidate(data)) {
                                    if (data.error == "0") {
                                        if (data.data.IsSet != 1) {
                                            //没有设置安全密码,提示设置安全密码
                                            if (data.data.IsCancelPayPasswordTip == 1) {
                                                //用户取消过设置密码弹窗则直接下单
                                                that.SubmitOrder();
                                            } else {
                                                //没有取消过设置密码弹窗则弹窗提示设置
                                                showCheckIsSetPayPasswordPop();
                                                //that.SubmitOrder();
                                            }
                                            return;
                                        } else {
                                            //已经设置了安全密码,提示输入安全密码
                                            showInputPayPasswordPop();
                                        }
                                    }
                                }
                            }
                        });
                    } else {
                        that.SubmitOrder();
                    }
                }
            }
                .method('checkValidate',
                    function () {
                        if (BENLAI.Model.OrderModels.CustSeletAddr==null||BENLAI.Model.OrderModels.CustSeletAddr.DistrictSysNo <= 0) {
                            this.alert({ msg: '请先确认地址信息', status: -1, callback: function () { smoothScroll(0, 500) } });
                            return false
                        }
                        if (BENLAI.Model.OrderTemp.AddrSelectList) {
                            this.alert({ msg: '请先选择地址信息', status: -1, callback: function () { smoothScroll(0, 500) } });
                            return false
                        }
                        if (BENLAI.Model.OrderModels.IsShowShenFen) {
                            //身份证正则表达式(18位) 
                            var isIDCard = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
                            var num = $('[shengtype="num"]').val();
                            var name = $('[shengtype="name"]').val();
                            if (name == "") {
                                this.alert({ msg: '请输入姓名', status: -1 });
                                return false;
                            }
                            if (num == "") {
                                this.alert({ msg: '请输入身份证号', status: -1 });
                                return false;
                            }
                            if (!isIDCard.test(num)) {
                                this.alert({ msg: '请输入正确的身份证', status: -1 });
                                return false;
                            }
                        }
                        if ($.trim($('#ConponCodeTxt').val()) != "" && !BENLAI.Model.OrderTemp.NoUseCoupon) {
                            BENLAI.Model.OrderTemp.GoTo = "#ConponCodeTxt";
                            this.ComfirmFun("您有已录入的优惠券" + $('#ConponCodeTxt').val() + "没有添加，请确认是否‘添加’？");
                            return false;
                        }
                        if (!BENLAI.Model.OrderTemp.confirmOk &&
                            BENLAI.Model.OrderModels.TotalNeedPay != 0 &&
                            BENLAI.Model.OrderModels.CanUseGiftCard > 0 &&
                            !$("#CBUseGiftCard").attr("checked")) {
                            BENLAI.Model.OrderTemp.GoTo = "#CBUseGiftCard";
                            BENLAI.Model.OrderTemp.confirmOk = true;
                            this.ComfirmFun("您有可以抵扣的礼金卡未使用");
                            return false;
                        }
                        if (($("#invoiceUl input[name='invoiceType']:checked").val() == 5 ||
                                $("#invoiceUl input[name='invoiceType']:checked").val() == 6) &&
                            $("#invoiceRequestUl input[name='requestInvoiceType']:checked").val() == 2) {
                            if (!$("#invoiceTitel").val()) {
                                this.alert({ msg: '公司全称必填', status: -1 });
                                return false;
                            }
                        }
                        var that = this;
                        var n = false;
                        this.ajax({
                            url: '/ajax/IsNeedAlertPhoneTan',
                            async: false,
                            success: function (data) {
                                if (data.status == 1) {
                                    n = true;
                                } else if (data.status == -2) {
                                    BENLAI.Model.AlertPhoneTemp
                                        .nextfun = function () { $.App.trigger('createOrder:submit'); }
                                    BENLAI.Model.AlertPhoneBind();
                                } else {
                                    that.ComfirmFun(data.msg);
                                }
                            }
                        })
                        return n;
                    }),
            SubmitPayPassword: function () {
                var that = this;
                var payPassword = $("#payPassword").val();
                payPassword = hex_md5(payPassword);
                //$.ajax({
                //    type: "POST",
                //    url: "/UserHome/CheckIsPayPasswordValid",
                //    data: { payPassword: payPassword },
                //    cache: false,
                //    success: function (data) {
                //        if (AjaxValidate(data)) {
                //            if (data.data.IsValid == 1) {
                //                hideInputPayPasswordPop();
                //                that.SubmitOrder();
                //            } else if (data.data.IsValid == 0) {
                //                hideInputPayPasswordPop();
                //                alert("支付密码输入错误");
                //                $("#payPassword").val("");
                //            } else if (data.error == 1) {
                //                window.location.href = "/login.html";
                //            } else {
                //                alert("错误信息：" + data.message);
                //            }
                //        }
                //        lazyLoad.Run();
                //    }
                //});
                that.SubmitOrder(payPassword);
            },
            SubmitOrder: function (payPwd) {
                var obj = {};
                obj.DistributionRequireType = $('[data-type="sendtime"]').attr("data-shipid");
                obj.PayType = $('[name=PayType]:checked').val();
                obj.IsPrintSOPrice = $('[name=printmoney]:checked').val();
                obj.ShengName = $('[shengtype="name"]').val();
                obj.ShengNum = $('[shengtype="num"]').val();
                obj.invoiceType = $("#invoiceUl input[name='invoiceType']:checked").val();
                obj.requestInvoiceType = $("#invoice_title input[name='requestInvoiceType']:checked").val();
                obj.invoiceTitle = $("#invoiceTitel").val();
                obj.PayPwd = payPwd;

                this.ajax({
                    url: '/NewShopping/CreateSplitOrder',
                    data: obj,
                    beforeSend: function () {
                        Loadding("show");
                    },
                    success: function (data) {
                        $("#payPassword").val("");
                        $("#inputPayPasswordPop").hide();
                        Loadding("hide");
                        if (Number(data.states) < 1) {
                            alert(data.msg);
                        } else {
                            _paq.push(['setCustomUrl', data.msg + '&action=submitorder']);
                            var prodList = "";
                            var criteo_ItemList = [];
                            $(eval(data.data.ItemHashList))
                                .each(function (k, v) {
                                    prodList += v.Sysno + "," + v.Quantity + ";";
                                    _paq.push([
                                        'addEcommerceItem',
                                        v.ProductID, // (required) SKU: Product unique identifier
                                        v.ProductName, // (optional) Product name
                                        v
                                        .C3Sysno,
// (optional) Product category. You can also specify an array of up to 5 categories eg. ["Books", "New releases", "Biography"]
                                        v.Price, // (recommended) Product price
                                        v.Quantity // (optional, default to 1) Product quantity
                                    ]);
                                    criteo_ItemList.push({
                                        id: v.ProductID,
                                        price: v.Price,
                                        quantity: v.Quantity
                                    });
                                })

                            //上报Criteo
                            window.criteo_q = window.criteo_q || [];
                            window.criteo_q.push(
                                    { event: "setAccount", account: criteoAccount },
                                    { event: "setEmail", email: customerId},
                                    { event: "setSiteType", type: "d" },
                                    { event: "trackTransaction", id: data.data.SOID, item:criteo_ItemList }
                            );
                            
                            _paq.push([
                                'trackEcommerceOrder', data.data.SysNos, data.data.TotalAmt + data.data.ShipPrice,
                                data.data.TotalAmt, 0, data.data.ShipPrice, false
                            ]);
                            _paq.push(['trackPageView']);
                            if (typeof DSPGoForOrderSuccess != 'undefined') {
                                DSPGoForOrderSuccess(data.data.SOID, data.data.TotalAmt, prodList);
                            }
                            try {
                                var products = $('.look_pop_sku tr td a[href]');
                                var productSysnos = [];
                                products.each(function () {
                                    var href = $(this).attr('href');
                                    var mtresult = /item-(\d+)/ig.exec(href);
                                    if (mtresult != null) {
                                        productSysnos.push(mtresult[1]);
                                    }
                                });
                                BIStatic.pushForCommitingOrder(productSysnos);
                            } catch (e) {

                            }
                            window.location.href = data.msg;
                        }
                    },
                    error: function () {
                        Loadding("hide");
                        $("#payPassword").val("");
                        $("#inputPayPasswordPop").hide();
                    }
                });
            },
            ComfirmFun: function (msg, title) {
                var t = title || "- 提示 -";
                var m = msg || "";
                $("#GiftCardWarning .title").html(t);
                $("#GiftCardWarning .del").html(m);

                if (msg.indexOf("礼金卡未使用") >= 0) {
                    var confirmText =
                        "<a class='pop_btn' style='margin-right:5px;' id='ComfirmOk' href='javascript:void(0)'><span>&nbsp;&nbsp;下次再说&nbsp;&nbsp;</span></a>";
                    confirmText +=
                        "<a id='ComfirmCancel' class='pop_btn mr15' href='javascript:void(0)'><span>&nbsp;&nbsp;去使用&nbsp;&nbsp;</span></a>";
                    $("#GiftCardWarning .pop_box .btn").css("width", "100%");
                    $("#GiftCardWarning .pop_box .btn").css("text-align", "center");
                    $("#GiftCardWarning .pop_box .btn").html(confirmText);
                    $("#GiftCardWarning .del").css("text-align", "center");
                } else {
                    var confirmText =
                        "<a id='ComfirmOk' class='pop_btn mr15' href='javascript:void(0)'><span>&nbsp;&nbsp;确定&nbsp;&nbsp;</span></a>";
                    confirmText +=
                        "<a class='pop_btn' id='ComfirmCancel' href='javascript:void(0)'><span>&nbsp;&nbsp;取消&nbsp;&nbsp;</span></a>";
                    $("#GiftCardWarning .pop_box .btn").html(confirmText);
                }

                ShowBack();
                $("#GiftCardWarning").show();
            },
            GiftUsedOk: function () {
                $("#GiftCardWarning").hide();
                HideBack();
                switch (BENLAI.Model.OrderTemp.GoTo) {
                    case "#ConponCodeTxt":
                        smoothScroll($(BENLAI.Model.OrderTemp.GoTo).offset().top - 100);
                        break;
                    case "#CBUseGiftCard":
                        this.createOrder();
                        break;
                    default:
                        break;
                }

            },
            GiftUsedCancel: function () {
                $("#GiftCardWarning").hide();
                HideBack();
                switch (BENLAI.Model.OrderTemp.GoTo) {
                    case "#ConponCodeTxt":
                        BENLAI.Model.OrderTemp.NoUseCoupon = true;
                        this.createOrder();
                        break;
                    case "#CBUseGiftCard":
                        smoothScroll($(BENLAI.Model.OrderTemp.GoTo).offset().top - 100);
                        break;
                    default:
                        break;
                }
            },
            position: function () {
                 var scrollTop = $(window).scrollTop();
                $(".new_all_submit")
                    .toggleClass("bottom_fixed",
                        scrollTop <
                        $("#fapiao").offset().top +
                        $("#fapiao").height() +
                        30 +
                        $(".new_all_submit").height() -
                        $(window).height());
                $(".new_all_submit")
                    .css({
                        left:
                            $("#CheckOut").offset().left + $("#CheckOut").width() - $(".new_all_submit").width() - 32
                    });

            },
            init: function () {

                BENLAI.Model.OrderTemp.OrderTemps = this.OrderTemps.val();
                if (!BENLAI.Model.OrderTemp.AddressListTemps2)
                    BENLAI.Model.OrderTemp.AddressListTemps2 = this.addressListtemp2.val();
                if (!BENLAI.Model.OrderTemp.AddressEditCreateTemp)
                    BENLAI.Model.OrderTemp.AddressEditCreateTemp = this.addressEditCreateTemp.val();
                if (!BENLAI.Model.OrderTemp.CellPhoneList)
                    BENLAI.Model.OrderTemp.CellPhoneList = this.CellPhoneList.val();
                if (!BENLAI.Model.OrderTemp.CellPhoneError)
                    BENLAI.Model.OrderTemp.CellPhoneError = this.CellPhoneError.val();
                BENLAI.Model.OrderTemp.PackageTimeSelect = [];
                BENLAI.Model.OrderTemp.IsSelectTime = false;
                this.bind.apply(this, arguments);
                $(window)
                    .bind("scroll resize orientationchange",
                        function () {
                            $.App.trigger("position:submit");
                        });
                $(document)
                    .bind("click",
                        function (event) {
                            event = event || window.event;
                            var target = $(event.target || event.srcElement);
                            if (target.attr("data-type") != "sendtime") {
                                if ($("[data-type=selectsendtime]:visible").length) {
                                    $(".new_send_time").find("[data-type=selectsendtime]").hide();
                                }
                            }

                        });
                var BFD_ITEM_INFO = {
                    active_name: "填写订单",
                    city: window.Cookies('DeliverySysNo').val() || 2
                };
                //setTimeout(function () {
                //    loadScript("http://static1.baifendian.com/service/benlai/bl_default.js");
                //}, 3000);
            }
        });
});

BENLAI.Shop.Invoice = {
    Invoice: function () {
        $("#fapiao")
            .CreateController({
                events: {
                    '#invoiceUl input[name="invoiceType"] click': 'CheckInvoiceType',
                    '[data-id="invoiceDesc"] click': 'ShowInvoiceDesc',
                    '#invoiceRequestUl input[name="requestInvoiceType"] click': 'CheckinvoiceRequest',
                    '#invoiceTitel blur': 'invoiceTitleBlur',
                    '#invoiceClose click': 'ClosePop'
                },
                CheckInvoiceType: function () {
                    var val = $("#invoiceUl input[name='invoiceType']:checked").val();
                    if (val == 5 || val == 6) {
                        $("#invoice_title").show("fast");
                        $("#invoice_paper").hide();
                    }
                        //if (val == 5) {
                        //    $("#invoice_title").show("fast");
                        //    $("#invoice_paper").hide();
                        //}
                        //else if (val == 6) {
                        //    $("#invoice_title").hide();
                        //    $("#invoice_paper").show("fast");
                        //}
                    else {
                        $("#invoice_title").hide();
                        $("#invoice_paper").hide();
                    }
                },
                CheckinvoiceRequest: function () {
                    var val = $("#invoiceRequestUl input[name='requestInvoiceType']:checked").val();
                    if (val == 1) {
                        $("#invoiceTitel").val("个人");
                        $("#invoiceTitel").removeAttr("placeHolder");
                    } else {
                        $("#invoiceTitel").val("");
                        $("#invoiceTitel").attr("placeHolder", "请输入公司全称");
                    }
                },
                invoiceTitleBlur: function () {
                    var val = $("#invoiceRequestUl input[name='requestInvoiceType']:checked").val();
                    if (val == 1 && !$("#invoiceTitel").val()) {
                        $("#invoiceTitel").val("个人");
                    }
                },
                ShowInvoiceDesc: function () {
                    ShowBack();
                    $("#invoiceDescription").show();
                },
                ClosePop: function () {
                    HideBack();
                    $("#invoiceDescription").hide();
                },
                init: function () {
                    $("#invoice_title").hide();
                    $("#invoice_paper").hide();
                    $("#invoiceDescription").hide();
                }
            });
    }
};

BENLAI.Shop.Orders = {
    Address: function () {
        $('#AddressView')
            .CreateController({
                events: {
                    '[data-type="edit"] click': 'listaddressedit',
                    '[data-type="delete"] click': 'deleteadrs',
                    '[data-type="phone"] focus': 'phonefocus',
                    '[data-type="phone"] blur': 'phoneblur',
                    '[data-input="text"] keyup': 'textkeyup',
                    '#district change': 'addressChange',
                    '#moreaddr click': 'moreaddress',
                    '#addaddr click': 'addaddress',
                    '[data-type="addr"] click': 'confirmadrs',
                    '#addrEClose click': 'cancelmodify',
                    '#area select change': 'areaChange',
                    '#cancelsubmit click': 'cancelmodify',
                    '#modifysubmit click': 'addrsubmit',
                    '#ddaddresstype .tab click': 'addresstypeClick',
                    '#addresstimetype .tab click': 'addresstimetypeClick'
                },
                moreaddress: function (t, event) {
                    var status = $(t).attr("status");
                    if (status == 1) {
                        $('[data-addid="AddressList2"]').show();
                        $(t).html("收回其他地址");
                        $(t).attr("status", "2");
                        BENLAI.Model.OrderTemp.z1 = true;
                    } else {
                        $('[data-addid="AddressList2"]').hide();
                        $(t).html("展开其他地址");
                        $(t).attr("status", "1");
                        BENLAI.Model.OrderTemp.z1 = false;
                    }
                },
                areaChange: function (t, event) {
                    if ($("#district").val() <= 0) {
                        $(t).parent().parent().find("em").show();
                    } else {
                        $(t).parent().parent().find("em").hide();
                    }
                },
                addaddress: function (t, event) {
                    BENLAI.Model.OrderModels.addressAdd = true;
                    ShowBack();
                    this.editadrs.call(this, t)
                },
                listaddressedit: function (t, event) {
                    BENLAI.Model.OrderModels.addressAdd = false;
                    ShowBack();
                    this.editadrs.call(this, t)
                },
                editadrs: function (t, event) {
              
                    var id = $(t).attr('data-id'), areaSysNo, depth, addressType, defaultDistribution;
                    if (id || id == 0) {
                        var dom = $('#MainEditAdr');
                        var datas = {};
                        dom.html('');
                        if (id > 0) {
                            for (var i = 0, len = BENLAI.Model.OrderModels.CustAdrr.length; i < len; i++) {
                                var sysno = BENLAI.Model.OrderModels.CustAdrr[i]['AddrSysNo'];
                                areaSysNo = BENLAI.Model.OrderModels.CustAdrr[i]['DistrictSysNo'];
                                if (sysno == id) {
                                    datas = BENLAI.Model.OrderModels.CustAdrr[i];
                                    addressType = BENLAI.Model.OrderModels.CustAdrr[i]['AddressType'];
                                    defaultDistribution = BENLAI.Model.OrderModels.CustAdrr[i]['DefaultDistribution'];
                                    break
                                }
                            }
                            depth = district;
                        } else {
                            areaSysNo =(  BENLAI.Model.OrderModels.CustSeletAddr!=null&&  BENLAI.Model.OrderModels.CustSeletAddr.DistrictSysNo > 0)
                                ? BENLAI.Model.OrderModels.CustSeletAddr.DistrictSysNo
                                : BENLAI.Model.OrderModels.DevliverySysNo;
                            depth = city;
                            if (BENLAI.Model.OrderModels.CustAdrr.length == 0)
                                datas.Phone = $('#defaultCellPhone').val();
                        }
                        this.tmpl({ dom: dom, v: BENLAI.Model.OrderTemp.AddressEditCreateTemp, datas: datas });
                        BENLAI.Model.OrderModels.EditAddrId = id;
                        $("#ddaddresstype input").hide();
                        $("#popTitle").text("新增地址");
                        if (!BENLAI.Model.OrderModels.addressAdd) {
                            $("#popTitle").text("修改地址");
                            $("#addressType").val(addressType);
                           // $("#assinTimeType").val(defaultDistribution);
                            $("#addresstimetype a").removeClass("on");
                            $("#ddaddresstype a").removeClass("on");
                            $("#ddaddresstype a")
                                .each(function () {
                                    if ($(this).attr("data-id") == addressType) {
                                        $(this).addClass("on");
                                    }
                                    if (addressType == 3) {
                                        $("#ddaddresstype input").show();
                                    } else {
                                        $("#ddaddresstype input").hide();
                                        $("#ddaddresstype input").val("");
                                    }
                                });
                            $("#addresstimetype a")
                                .each(function () {
                                    if ($(this).attr("data-id") == defaultDistribution) {
                                        $(this).addClass("on");
                                    }
                                });
                        }
                        this.updateView(function () { });
                        var isCityFull = BENLAI.Model.OrderModels.IsCityFull == true ? 1 : 0;
                        BENLAI.Model.OrderTemp.Netwide = isCityFull
                        BENLAI.Model.OrderTemp.GIndex = 1;
                        getArea(depth, areaSysNo, isCityFull, 1);
                        //smoothScroll($("#addresEdit").offset().top);
                        dom.find("em").hide();
                        BENLAI.Model.OrderModels.Editing = true;
                        $('#MainEditAdr').show();
                    }
                },
                deleteadrs: function (t, event) {
                    var id = $(t).attr('data-id'), that = this;
                    if (id) {
                        if (!confirm('您确定要删除该地址信息吗？'))
                            return;
                        this.ajax({
                            url: '/newshopping/DeleteAddress',
                            data: { SysNo: id },
                            success: function (data) {
                                if (data.status == 1) {
                                    BENLAI.Model.OrderModels = data.data;
                                    if (Number(BENLAI.Model.OrderModels.IsUseConpon) == 0)
                                        BENLAI.Model.OrderTemp.CouponShow = false;
                                    $.App.trigger('bind:order');
                                    if (!data.msg.IsNullOrEmpty())
                                        that.alert(data);
                                } else {
                                    that.alert(data)
                                }
                            }
                        })
                    }
                },
                addrsubmit: function (t, event) {
                    var id = BENLAI.Model.OrderModels.EditAddrId,
                        that = this,
                        data = {},
                        url = '/newshopping/ModifyAndAddAddress';
                    data = this.addrsubmit.checkAddress.apply(this, arguments);
                    if (data) {
                        this.ajax({
                            url: url,
                            data: data,
                            success: function (data) {
                                if (data.status == 1) {
                                    if (data.data) {
                                        BENLAI.Model.OrderModels = data.data;
                                        if (Number(BENLAI.Model.OrderModels.IsUseConpon) == 0)
                                            BENLAI.Model.OrderTemp.CouponShow = false;
                                        that.cancelmodify.call(that, t);
                                        $.App.trigger('bind:order');
                                    }
                                }
                                if (data.msg)
                                    //that.alert(data);
                                    $("#msg").html(data.msg);
                                $("#msg").show();
                                if (data.refresh == 1)
                                    window.location = window.location;
                            }
                        })
                    }
                }.method('checkAddress',
                    function () {
                        var Info = {},
                            $t = this,
                            receiveName = $t.ReceiveName,
                            a = $('#district').val(),
                            adress = $t.Address,
                            cellphone = $t.CellPhone,
                            c = $t.regExp.cellPhone,
                            p = $t.regExp.phone 
                           // brief = $t.Brief
                                ;

                        Info['Info.AddressSysNo'] = BENLAI.Model.OrderModels.EditAddrId;
                        if (BENLAI.Model.OrderModels.addressAdd)
                            Info['Info.AddressSysNo'] = 0;
                        Info['Info.Name'] = $.trim(receiveName.val());
                        if (!Info['Info.Name']) {
                            receiveName.focus().parent().find('em').show();
                            return false
                        }
                        if (a <= 0) {
                            $('#district').focus().parent().find('em').show();
                            return false
                        }
                        Info['Info.Address'] = $.trim(adress.val());
                        if (!Info['Info.Address']) {
                            adress.focus().parent().find('em').show();
                            return false
                        }
                        Info['Info.CellPhone'] = $.trim(cellphone.val());
                        if (Info['Info.CellPhone']) {
                            var key = c.test(Info['Info.CellPhone']);
                            if (key == false) {
                                cellphone.focus().parent().find('em').show();
                                return false
                            }
                        }
                        Info.areacode = $.trim($.trim($t.areacode.val()) != $t.areacode.attr('data-text')
                            ? $t.areacode.val()
                            : '');
                        Info.phonecode = $.trim($.trim($t.phonecode.val()) != $t.phonecode.attr('data-text')
                            ? $t.phonecode.val()
                            : '');
                        Info.extencode = $.trim($.trim($t.extencode.val()) != $t.extencode.attr('data-text')
                            ? $t.extencode.val()
                            : '');
                        if (Info.areacode || Info.phonecode || Info.extencode) {
                            Info['Info.Phone'] = Info.areacode +
                                '-' +
                                Info.phonecode +
                                (Info.extencode ? '-' + Info.extencode : '');
                            if (!p.test(Info['Info.Phone'])) {
                                cellphone.parent().find('em').show();
                                return false
                            }
                        }
                        if (!Info['Info.CellPhone'] && !Info['Info.Phone']) {
                            cellphone.focus().parent().find('em').show();
                            return false
                        }
                        Info['Info.GroupIndex'] = 1;
                        Info['Info.AreaSysNo'] = a;
                        if (!a || a == 0) {
                            $('#district').parent().find('em').show();
                            return false
                        }
                        if ($("#ddaddresstype .on").length > 0 && $("#addressType").val() == 3
                            //&& !$.trim(brief.val() )
                        ) {
                            $("#ddaddresstype em").show();
                            return false;
                        }
                        //Info['Info.Brief'] = $.trim(brief.val());
                        Info['Info.AddressType'] = $("#addressType").val();
                        //Info['Info.DefaultDistribution'] = $("#assinTimeType").val();
                        Info['Info.IsDefault'] = $t.Default.attr("checked") ? 1 : 0;
                        return Info
                    }),
                cancelmodify: function (t, event) {
                    $("#MainEditAdr").hide();
                    HideBack();
                    $("#MainEditAdr").html('');
                    BENLAI.Model.OrderModels.Editing = false;
                },
                confirmadrs: function (t, event) {
                    if (BENLAI.Model.OrderModels.Editing) return false;
                    var id = $(t).attr("data-id"), that = this, dt = {}, url = '/newshopping/SelectAddress';
                    dt.SysNo = id;
                    dt.IsYuShou = 0;
                    dt.GroupIndex = -1;
                    if (!id) {
                        alert("请选择地址后再确认！");
                        return false;
                    }
                    if (dt) {
                        this.ajax({
                            url: url,
                            data: dt,
                            success: function (data) {
                                if (data.status == 1) {
                                    if (data.data) {
                                        BENLAI.Model.OrderModels = data.data;
                                        if (Number(BENLAI.Model.OrderModels.IsUseConpon) == 0)
                                            BENLAI.Model.OrderTemp.CouponShow = false;
                                        $.App.trigger('bind:order');
                                    }
                                }
                                if (!data.msg.IsNullOrEmpty())
                                    that.alert(data);
                                if (data.refresh == 1)
                                    window.location = window.location;
                            }
                        })
                    }
                    BENLAI.Model.OrderTemp.AddrSelectList = false;
                },
                phonefocus: function (t, event) {
                    var dt = $(t).attr('data-text');
                    if ($(t).val() == dt) {
                        $(t).val('')
                    }
                },
                phoneblur: function (t, event) {
                    var dt = $(t).attr('data-text');
                    if ($(t).val().IsNullOrEmpty()) {
                        $(t).val(dt)
                    }
                },
                textkeyup: function (t, event) {
                    var v = $.trim($(t).val()), type = $(t).attr('data-type'), msg = $(t).attr('data-msg');
                    if (v.IsNullOrEmpty()) {
                        if (type == 'zip' && type != 'phone') {
                            $(t).parent().find('em').hide()
                        } else {
                            $(t).parent().find('em').show()
                        }
                    } else {
                        if (type == 'cellphone' && !this.regExp.cellPhone.test(v)) {
                            $(t).parent().find('em').html(msg).show()
                        } else if (type == 'phone') {
                            var Info = {};
                            Info.areacode = $.trim($.trim(this.areacode.val()) != this.areacode.attr('data-text')
                                ? this.areacode.val()
                                : '');
                            Info.phonecode = $.trim($.trim(this.phonecode.val()) != this.phonecode.attr('data-text')
                                ? this.phonecode.val()
                                : '');
                            Info.extencode = $.trim($.trim(this.extencode.val()) != this.extencode.attr('data-text')
                                ? this.extencode.val()
                                : '');
                            if (Info.areacode || Info.phonecode || Info.extencode) {
                                Info['Phone'] = Info.areacode +
                                    '-' +
                                    Info.phonecode +
                                    (!Info.extencode.IsNullOrEmpty() ? '-' + Info.extencode : '');
                                if (!this.regExp.phone.test(Info['Phone'])) {
                                    $(t).parent().find('em').html(msg).show();
                                    return false
                                }
                            }
                            $(t).parent().find('em').hide()
                        } else
                            $(t).parent().find('em').hide()
                    }
                },
                addressChange: function (t, event) {
                    var v = $(t).val(), dom = $(t).parent().parent().find('em');
                    if (v <= 0) {
                        dom.show();
                    } else {
                        dom.hide();
                    }
                },
                addresstypeClick: function (t, event) {
                    $("#ddaddresstype .tab").removeClass('on');
                    $(t).addClass("on");
                    $("#addressType").val($(t).attr("data-id"));
                    if ($(t).attr("data-id") == 3) {
                        $("#ddaddresstype input").show();
                    } else {
                        $("#ddaddresstype input").hide();
                    }
                },
                addresstimetypeClick: function (t, event) {
                    $("#addresstimetype .tab").removeClass('on');
                    $(t).addClass("on");
                    $("#assinTimeType").val($(t).attr("data-id"));
                },
                init: function () {
                      
                    if (BENLAI.Model.OrderModels.CustSeletAddr == null||BENLAI.Model.OrderModels.CustSeletAddr.DistrictSysNo <= 0) {
                        $("#addaddr").trigger("click");
                        $("#addrEClose").hide();
                        $("#cancelsubmit").hide();
                    }
                }
            })
    },
    Package: function () {
        $('#PackageView')
            .CreateController({
                events: {
                    '.send_look_tit click': 'PackageDetailExpand',
                    '.look_pop_tit a click': 'PackageDetailClose',
                    '[data-type="sendtime"] click': 'PackageTimeExpand',
                    '[data-type="selectsendtime"] a click': 'PackageTimeSelect',
                    '[data-type="setDanAddress"] click': 'SetPackageAddress',
                    '[data-type="phone"] focus': 'phonefocus',
                    '[data-type="phone"] blur': 'phoneblur',
                    '[data-input="text"] keyup': 'textkeyup',
                    '[data-type="edit2"] click': 'listaddressedit',
                    '[data-type="delete2"] click': 'deleteadrs',
                    '[data-type="addr2"] click': 'selectAddress',
                    '#pclose click': 'ClosePackageAddress',
                    '#moreaddr2 click': 'moreaddress',
                    '#addaddr2 click': 'addaddress',
                    '#confirmAdrs2 click': 'confirmadrs2',
                    '#cancelsubmit click': 'cancelmodify',
                    '#modifysubmit click': 'addrsubmit'
                },
                PackageDetailExpand: function (t, event) {
                    ShowBack();
                    var y = $(t).parent().position().top;
                    $(t).parent().next().css({ top: y - 14 }).show();
                },
                PackageDetailClose: function (t, event) {
                    HideBack();
                    $(t).parent().parent().hide();
                },
                PackageTimeExpand: function (t, event) {

                    if ($(t).parent().next().is(":hidden")) {
                        $('[data-type="selectsendtime"]').hide();
                        $(t).parent().next().show();
                    } else {
                        $(t).parent().next().hide();
                    }
                },
                PackageTimeSelect: function (t, event) {
                    
                    $(t).parent().hide();
                    var selecthtml = $(t).html();
                    var no = $(t).attr("data-shipid");
                    $(t).parent().prev().find("a").html(selecthtml);
                    $(t).parent().prev().find("a").attr("data-shipid", no);
                    $('[data-id="pfdrd"]').html($(t).attr("data-remark"));

                    var packid = $(t).attr('data-packid');
                    var obj = {};
                    obj.packid = packid;
                    obj.shipType = no;
                    this.ajax({
                        url: '/NewShopping/ChangeShip',
                        data: obj,
                        beforeSend: function () {
                            Loadding("show");
                        },
                        success: function (data) {
                            Loadding("hide");
                            if (data.Code !== 1) {
                                alert(data.Message);
                            }
                        },
                        error: function () {
                            Loadding("hide"); 
                        }
                    });

                    if (packid == 1) {
                        BENLAI.Model.OrderTemp.PackageTimeSelect = no;
                    }

                },
                SetPackageAddress: function (t, event) {
                    BENLAI.Model.OrderTemp.PackageAddressGroupIndex = Number($(t).attr("pno"));
                    BENLAI.Model.OrderModels.Editing = false;
                    this.bindList.call(this, t);
                    ShowBack();
                    $("#YuShouEditAdr").show();
                    smoothScroll($("#YuShouEditAdr").offset().top);
                },
                ClosePackageAddress: function (t, event) {
                    BENLAI.Model.OrderModels.Editing2 = false;
                    $("#YuShouEditAdr").html('');
                    $("#YuShouEditAdr").hide();
                    HideBack();
                    $.App.trigger('bind:order');
                },
                moreaddress: function (t, event) {
                    var status = $(t).attr("status");
                    if (status == 1) {
                        $("[data-n2bid='n']").show();
                        $(t).html("收回其他地址");
                        $(t).attr("status", "2");
                        BENLAI.Model.OrderTemp.z2 = true;
                    } else {
                        $("[data-n2bid='n']").hide();
                        $(t).html("展开其他地址");
                        $(t).attr("status", "1");
                        BENLAI.Model.OrderTemp.z2 = false;
                    }
                },
                addaddress: function (t, event) {
                    $("#TanAddr").html('<div id="addresEdit2" class="new_adr_in"></div>');
                    BENLAI.Model.OrderModels.paddressAdd = true;
                    this.editadrs.call(this, t)
                },
                listaddressedit: function (t, event) {
                    $("#TanAddr").html('<div id="addresEdit2" class="new_adr_in"></div>');
                    BENLAI.Model.OrderModels.paddressAdd = false;
                    this.editadrs.call(this, t)
                },
                editadrs: function (t, event) {
                    var id = $(t).attr('data-id'), areaSysNo, depth;
                    var Index = BENLAI.Model.OrderTemp.PackageAddressGroupIndex - 1;
                    if (id || id == 0) {
                        var dom = $('#addresEdit2');
                        var datas = {};
                        dom.html('');
                        if (id > 0) {
                            for (var i = 0, len = BENLAI.Model.OrderModels.Child[Index].AddrList.length;
                                i < len;
                                i++) {
                                var sysno = BENLAI.Model.OrderModels.Child[Index].AddrList[i]['AddrSysNo'];
                                areaSysNo = BENLAI.Model.OrderModels.Child[Index].AddrList[i]['DistrictSysNo'];
                                if (sysno == id) {
                                    datas = BENLAI.Model.OrderModels.Child[Index].AddrList[i];
                                    break;
                                }
                            }
                            depth = district;
                        } else {
                            areaSysNo = BENLAI.Model.OrderModels.DevliverySysNo;
                            depth = city;
                        }
                        this.tmpl({ dom: dom, v: BENLAI.Model.OrderTemp.AddressEditCreateTemp, datas: datas });
                        BENLAI.Model.OrderModels.PackEditAddrId2 = id;
                        this.updateView(function () { });
                        BENLAI.Model.OrderTemp.Netwide = BENLAI.Model.OrderModels.Child[Index].IsFullCity;
                        BENLAI.Model.OrderTemp.GIndex = Index + 1;
                        getArea(depth, areaSysNo, BENLAI.Model.OrderModels.Child[Index].IsFullCity, Index + 1);
                        //smoothScroll($("#addresEdit2").offset().top);
                        dom.find("font").hide();
                        $("#addrECloseDiv").hide();
                        BENLAI.Model.OrderModels.Editing2 = true;
                    }
                },
                deleteadrs: function (t, event) {
                    var id = $(t).attr('data-id'), that = this;
                    if (id) {
                        if (!confirm('您确定要删除该地址信息吗？'))
                            return;
                        this.ajax({
                            url: '/newshopping/DeleteAddress',
                            data: { SysNo: id },
                            success: function (data) {
                                if (data.status == 1) {
                                    BENLAI.Model.OrderModels = data.data;
                                    that.bindList.call(that, t);
                                    if (!data.msg.IsNullOrEmpty())
                                        that.alert(data);
                                } else {
                                    that.alert(data)
                                }
                            }
                        })
                    }
                },
                addrsubmit: function (t, event) {
                    var id = BENLAI.Model.OrderModels.EditAddrId,
                        that = this,
                        data = {},
                        url = '/newshopping/ModifyAndAddAddress';
                    data = this.addrsubmit.checkAddress.apply(this, arguments);
                    if (data) {
                        this.ajax({
                            url: url,
                            data: data,
                            success: function (data) {
                                if (data.status == 1) {
                                    if (data.data) {
                                        BENLAI.Model.OrderModels = data.data;
                                        that.bindList.call(that, t);
                                    }
                                }
                                if (!data.msg.IsNullOrEmpty())
                                    that.alert(data);
                                if (data.refresh == 1)
                                    window.location = window.location;
                            }
                        })
                    }
                }.method('checkAddress',
                    function () {
                        var Info = {},
                            $t = this,
                            z = $t.regExp.zipCode,
                            c = $t.regExp.cellPhone,
                            p = $t.regExp.phone,
                            a = $('#district').val(),
                            //brief = $t.Brief,
                            zip = $t.Zip,
                            adress = $t.Address,
                            receiveName = $t.ReceiveName,
                            cellphone = $t.CellPhone;
                        Info['Info.AddressSysNo'] = BENLAI.Model.OrderModels.PackEditAddrId2;
                        if (BENLAI.Model.OrderModels.paddressAdd)
                            Info['Info.AddressSysNo'] = 0;
                        //Info['Info.Brief'] = $.trim(brief.val());
                        if (a <= 0) {
                            $('#district').focus().parent().parent().find('font').show();
                            return false
                        }
                        //if (Info['Info.Brief'].IsNullOrEmpty()) {
                        //    brief.focus().parent().find('font').show();
                        //    return false
                        //}
                        Info['Info.AreaSysNo'] = a;
                        if (!a || a == 0) {
                            $('#district').parent().find('font').show();
                            //brief.focus();
                            return false
                        }
                        Info['Info.GroupIndex'] = BENLAI.Model.OrderTemp.PackageAddressGroupIndex;
                        Info['Info.Zip'] = $.trim(zip.val());
                        if (Info['Info.Zip'] && !z.test(Info['Info.Zip'])) {
                            zip.focus().parent().find('font').show();
                            return false
                        }
                        Info['Info.Address'] = $.trim(adress.val());
                        if (Info['Info.Address'].IsNullOrEmpty()) {
                            adress.focus().parent().find('font').show();
                            return false
                        }
                        Info['Info.Name'] = $.trim(receiveName.val());
                        if (Info['Info.Name'].IsNullOrEmpty()) {
                            receiveName.focus().parent().find('font').show();
                            return false
                        }
                        Info['Info.CellPhone'] = $.trim(cellphone.val());
                        if (Info['Info.CellPhone']) {
                            var key = c.test(Info['Info.CellPhone']);
                            if (key == false) {
                                cellphone.focus().parent().find('p').html(cellphone.attr('data-msg')).show();
                                return false
                            }
                        }
                        Info.areacode = $.trim($.trim($t.areacode.val()) != $t.areacode.attr('data-text')
                            ? $t.areacode.val()
                            : '');
                        Info.phonecode = $.trim($.trim($t.phonecode.val()) != $t.phonecode.attr('data-text')
                            ? $t.phonecode.val()
                            : '');
                        Info.extencode = $.trim($.trim($t.extencode.val()) != $t.extencode.attr('data-text')
                            ? $t.extencode.val()
                            : '');
                        if (Info.areacode || Info.phonecode || Info.extencode) {
                            Info['Info.Phone'] = Info.areacode +
                                '-' +
                                Info.phonecode +
                                (!Info.extencode.IsNullOrEmpty() ? '-' + Info.extencode : '');
                            if (!p.test(Info['Info.Phone'])) {
                                cellphone.parent().find('font').html($t.extencode.attr('data-msg')).show();
                                return false
                            }
                        }
                        if (Info['Info.CellPhone'].IsNullOrEmpty() && Info['Info.Phone'].IsNullOrEmpty()) {
                            cellphone.focus().parent().find('font').html('收货手机和电话至少填一项').show();
                            return false
                        }
                        Info['Info.IsDefault'] = $t.Default.attr("checked") ? 1 : 0;
                        return Info
                    }),
                cancelmodify: function (t, event) {
                    BENLAI.Model.OrderModels.Editing2 = false;
                    this.bindList.call(this, t);
                },
                confirmadrs2: function (t, event) {
                    var id = $('.adr_tab_on[data-type="addr2"]').attr('data-id');
                    dt = {};
                    dt.SysNo = id;
                    dt.GroupIndex = BENLAI.Model.OrderTemp.PackageAddressGroupIndex;
                    var no = dt.GroupIndex - 1;
                    dt.IsYuShou = BENLAI.Model.OrderModels.Child[no].IsYuShou;
                    if (!id) {
                        alert("请选择地址后再确认！");
                        return false;
                    }
                    $("[data-wenzino ='yushou" + dt.GroupIndex + "']")
                        .html(BENLAI.Model.OrderModels.Child[no].SelectAddr);
                    this.ClosePackageAddress.call(this, t);
                },
                selectAddress: function (t, event) {
                    if (BENLAI.Model.OrderModels.Editing2) return false;
                    var id = $(t).attr('data-id'), that = this, dt = {}, url = '/newshopping/SelectAddress';
                    dt.SysNo = id;
                    dt.GroupIndex = BENLAI.Model.OrderTemp.PackageAddressGroupIndex;
                    var no = dt.GroupIndex - 1;
                    dt.IsYuShou = BENLAI.Model.OrderModels.Child[no].IsYuShou;
                    if (dt) {
                        this.ajax({
                            url: url,
                            data: dt,
                            success: function (data) {
                                if (data.status == 1) {
                                    if (data.data) {
                                        BENLAI.Model.OrderModels = data.data;
                                        that.bindList.call(that, t);
                                    }
                                }
                                if (!data.msg.IsNullOrEmpty())
                                    that.alert(data);
                                if (data.refresh == 1)
                                    window.location = window.location;
                            }
                        });
                    }
                },
                phonefocus: function (t, event) {
                    var dt = $(t).attr('data-text');
                    if ($(t).val() == dt) {
                        $(t).val('')
                    }
                },
                phoneblur: function (t, event) {
                    var dt = $(t).attr('data-text');
                    if ($(t).val().IsNullOrEmpty()) {
                        $(t).val(dt)
                    }
                },
                textkeyup: function (t, event) {
                    var v = $.trim($(t).val()), type = $(t).attr('data-type'), msg = $(t).attr('data-msg');
                    if (v.IsNullOrEmpty()) {
                        if (type == 'zip' && type != 'phone') {
                            $(t).parent().find('font').hide()
                        } else {
                            $(t).parent().find('font').show()
                        }
                    } else {
                        if (type == 'zip' && !this.regExp.zipCode.test(v)) {
                            $(t).parent().find('font').show()
                        } else if (type == 'cellphone' && !this.regExp.cellPhone.test(v)) {
                            $(t).parent().find('font').html(msg).show()
                        } else if (type == 'phone') {
                            var Info = {};
                            Info.areacode = $.trim($.trim(this.areacode.val()) != this.areacode.attr('data-text')
                                ? this.areacode.val()
                                : '');
                            Info.phonecode = $.trim($.trim(this.phonecode.val()) != this.phonecode.attr('data-text')
                                ? this.phonecode.val()
                                : '');
                            Info.extencode = $.trim($.trim(this.extencode.val()) != this.extencode.attr('data-text')
                                ? this.extencode.val()
                                : '');
                            if (Info.areacode || Info.phonecode || Info.extencode) {
                                Info['Phone'] = Info.areacode +
                                    '-' +
                                    Info.phonecode +
                                    (!Info.extencode.IsNullOrEmpty() ? '-' + Info.extencode : '');
                                if (!this.regExp.phone.test(Info['Phone'])) {
                                    $(t).parent().find('font').html(msg).show();
                                    return false
                                }
                            }
                            $(t).parent().find('font').hide()
                        } else
                            $(t).parent().find('font').hide()
                    }
                },
                bindList: function (t, event) {
                    var no = BENLAI.Model.OrderTemp.PackageAddressGroupIndex - 1;
                    this.tmpl({
                        dom: $("#YuShouEditAdr"),
                        v: BENLAI.Model.OrderTemp.AddressListTemps2,
                        datas: BENLAI.Model.OrderModels.Child[no]
                    });
                    if (BENLAI.Model.OrderTemp.z2) {
                        $("[data-n2bid='n']").show();
                        $("#moreaddr2").html("收回其他地址");
                        $("#moreaddr2").attr("status", "2");
                    }
                },
                checkArrivalToday: function (t, event) {
                 
                    var that = this;
                    if (BENLAI.Model.OrderModels.Child[0].CheckShipTime) {
                        var AddressSysno = BENLAI.Model.OrderModels.Child[0].SelectAddrSysNo;
                        this.ajax({
                            url: '/Vtp/IsArrivalToday',
                            data: { AddressSysno: AddressSysno },
                            success: function (data) {
                                if (data.status == 1) {
                                    that.PackageTimeSelect($('#PackageView')
                                        .find('tr')
                                        .eq(1)
                                        .find('[data-type="selectsendtime"] [data-shipid="0"]'),
                                        'click');
                                } else {
                                    that.PackageTimeSelect($('#PackageView')
                                        .find('tr')
                                        .eq(1)
                                        .find('[data-type="selectsendtime"] [data-shipid="1"]'),
                                        'click');
                                    $('#PackageView')
                                        .find('tr')
                                        .eq(1)
                                        .find('[data-type="selectsendtime"] [data-shipid="0"]')
                                        .remove();

                                }
                            }

                        })
                    }
                },
                init: function () {
                    this.checkArrivalToday();
                }
            })
    },
    Pay: function () {
        $('#PayView')
            .CreateController({
                events: {
                    '#CBUseScore click': 'UseScore',
                    '#CBUseBalance click': 'UseBalance',
                    '#CBUseGiftCard click': 'UseGiftCard',
                    '#MoreGiftCard click': 'ChongGiftCard',
                    '#CouponPage a click': 'SelectPageNum',
                    '#GoToPage click': 'GoToPageNum',
                    '#pageTxt keyup': 'CheckNum',
                    '[data-id="CouponInfoList"] [type="radio"] click': 'CheckCoupon',
                    '#UseCouponBtn click': 'PutUseCoupon',
                    '#TxtUseScore keyup': 'UseScoreChange',
                    '#TxtUseBalance keyup': 'UseBalanceChange',
                    '#TxtUseGiftCard keyup': 'UseGiftCardChange',
                    '#TxtUseScore blur': 'UseScore',
                    '#TxtUseBalance blur': 'UseBalance',
                    '#TxtUseGiftCard blur': 'UseGiftCard',
                    '#[name=PayType] click': 'selectPayType',
                    '#UseCouponCB click': 'ShowCoupon',
                    '#TiJiao click': 'CellPhoneOk',
                    '#QuXiao click': 'CancelPhone',
                    '#QueDing click': 'CancelPhone',
                    '#YanZhengMa click': 'SendSMS',
                    '#ConponCodeTxt blur': 'ZiNum',
                    '#GiftCardPwd blur': 'ZiNum',
                    '#GiftCardId keyup': 'NumXiaoYan'
                },
                UseScore: function (m, event) {
                    var n = $(m).attr("type");
                    var t = "#CBUseScore";
                    var show = $(t).attr("checked");

                    var wen = $(t).parent().next().next().find(".payment_word02");
                    var that = this;
                    var score = $("#TxtUseScore").val();
                    if (!show && BENLAI.Model.OrderModels.MustUseJiFen > 0) {
                        $(t).attr("checked", true);
                        alert("商品中存在仅积分支付商品，不能取消积分使用！");
                        return false;
                    }
                    if (show && BENLAI.Model.OrderModels.TotalCanUseJiFen <= 0) {
                        $(t).attr("checked", false);
                        alert("您的有效积分为0，不能使用积分！");
                        return false;
                    }
                    if (show &&
                        Number(score) < BENLAI.Model.OrderModels.MustUseJiFen &&
                        BENLAI.Model.OrderModels.MustUseJiFen > 0) {
                        $("#TxtUseScore").val(BENLAI.Model.OrderModels.MustUseJiFen);
                        wen.html("-" + $.BENLAI.toPrice(BENLAI.Model.OrderModels.MustUseJiFenAmt));
                        $(t).attr("checked", true);
                        alert("不能使用低于最低需要使用的积分！")
                        return false;
                    }
                    if (show &&
                        Number(score) > BENLAI.Model.OrderModels.CanUseJiFen &&
                        ((Number(score) != BENLAI.Model.OrderModels.MustUseJiFen &&
                                BENLAI.Model.OrderModels.MustUseJiFen > 0) ||
                            BENLAI.Model.OrderModels.MustUseJiFen <= 0)) {
                        $("#TxtUseScore").val(BENLAI.Model.OrderModels.UsedJiFen);
                        wen.html("-" + $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedJiFenAmt));
                        alert("超出可使用的积分！");
                        return false;
                    }
                    if (show && score <= 0 && n == "text") {
                        $(t).attr("checked", false);
                        show = false;
                    }
                    if (show) {
                        this.ajax({
                            url: '/newshopping/UseScore',
                            data: { score: score },
                            success: function (data) {
                                if (data.status == 1) {
                                    BENLAI.Model.OrderModels = data.data;
                                    $(t).parent().next().next().show();
                                    $("#TxtUseScore").val(BENLAI.Model.OrderModels.UsedJiFen);
                                    wen.html("-" + $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedJiFenAmt))
                                    $("#TotalScorePay")
                                        .html("- 账户积分支付<b>" +
                                            $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedJiFenAmt) +
                                            "</b>元");
                                    that.ChangeSBG.call(that, t);
                                } else {
                                    $("#TxtUseScore").val(BENLAI.Model.OrderModels.UsedJiFen);
                                    wen.html("-" + $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedJiFenAmt))
                                    $(t).attr("checked", false);
                                    that.alert(data);
                                }
                            }
                        });
                    } else {
                        this.ajax({
                            url: '/newshopping/CancelUseScore',
                            data: {},
                            success: function (data) {
                                if (data.status == 1) {
                                    BENLAI.Model.OrderModels = data.data;
                                    $(t).parent().next().next().hide();
                                    $("#TxtUseScore").val(0);
                                    wen.html("-" + $.BENLAI.toPrice(0))
                                    $("#TotalScorePay").html('');
                                    that.ChangeSBG.call(that, t);
                                } else {
                                    that.alert(data);
                                }
                            }
                        });
                    }
                },
                UseBalance: function (m, event) {
                    var n = $(m).attr("type");
                    var t = "#CBUseBalance";
                    var show = $(t).attr("checked");
                    var wen = $(t).parent().next().next().find(".payment_word02");
                    var that = this;
                    var Balance = $("#TxtUseBalance").val();
                    if (show && BENLAI.Model.OrderModels.TotalCanUseYuE <= 0) {
                        $(t).attr("checked", false);
                        alert("您的余额为0元，不能使用余额！");
                        return false;
                    }
                    if (Number(Balance) > BENLAI.Model.OrderModels.CanUseYuE) {
                        $("#TxtUseBalance").val(BENLAI.Model.OrderModels.UsedYuE);
                        wen.html("-" + $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedYuE))
                        alert("超出可使用的余额！");
                        return false;
                    }
                    if (show && Balance <= 0 && n == "text") {
                        $(t).attr("checked", false);
                        show = false;
                    }
                    if (show) {
                        this.ajax({
                            url: '/newshopping/UseBalance',
                            data: { Balance: Balance },
                            success: function (data) {
                                if (data.status == 1) {
                                    BENLAI.Model.OrderModels = data.data;
                                    $(t).parent().next().next().show();
                                    $("#TxtUseBalance").val(BENLAI.Model.OrderModels.UsedYuE);
                                    wen.html("-" + $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedYuE))
                                    $("#TotalBalancePay")
                                        .html("- 账户余额支付<b>" +
                                            $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedYuE) +
                                            "</b>元");
                                    that.ChangeSBG.call(that, t);
                                } else {
                                    $("#TxtUseBalance").val(BENLAI.Model.OrderModels.UsedYuE);
                                    wen.html("-" + $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedYuE))
                                    $(t).attr("checked", false);
                                    that.alert(data);
                                }
                            }
                        });
                    } else {
                        this.ajax({
                            url: '/newshopping/CancelBalance',
                            data: {},
                            success: function (data) {
                                if (data.status == 1) {
                                    BENLAI.Model.OrderModels = data.data;
                                    $(t).parent().next().next().hide();
                                    $("#TxtUseBalance").val(0);
                                    wen.html("-" + $.BENLAI.toPrice(0))
                                    $("#TotalBalancePay").html('');
                                    that.ChangeSBG.call(that, t);
                                } else {
                                    that.alert(data)
                                }
                            }
                        });
                    }
                },
                UseGiftCard: function (m, event) {
                    var n = $(m).attr("type");
                    var t = "#CBUseGiftCard";
                    var show = $(t).attr("checked");
                    var wen = $(t).parent().next().next().find(".payment_word02");
                    var that = this;
                    var GiftCard = $("#TxtUseGiftCard").val();
                    if (Number(GiftCard) > BENLAI.Model.OrderModels.CanUseGiftCard) {
                        $("#TxtUseGiftCard").val(BENLAI.Model.OrderModels.UsedGiftCard);
                        wen.html("-" + $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedGiftCard))
                        alert("超出可使用的礼金卡余额！");
                        return false;
                    }
                    if (show && GiftCard <= 0 && n == "text") {
                        $(t).attr("checked", false);
                        show = false;
                    }
                    if (show) {
                        if (BENLAI.Model.OrderModels.TotalCanUseGiftCard <= 0) {
                            $(t).attr("checked", false);
                            alert("您没有礼金卡，请充值后重试！");
                            return false;
                        }
                        this.ajax({
                            url: '/newshopping/UseGiftCard',
                            data: { GiftCard: $("#TxtUseGiftCard").val() },
                            success: function (data) {
                                if (data.status == 1) {
                                    BENLAI.Model.OrderModels = data.data;
                                    $(t).parent().next().next().show();
                                    $("#TxtUseGiftCard").val(BENLAI.Model.OrderModels.UsedGiftCard);
                                    wen.html("-" + $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedGiftCard))
                                    $("#TotalGiftCardPay")
                                        .html("- 账户礼金卡支付<b>" +
                                            $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedGiftCard) +
                                            "</b>元");
                                    that.ChangeSBG.call(that, t);
                                } else {
                                    $("#TxtUseGiftCard").val(BENLAI.Model.OrderModels.UsedGiftCard);
                                    wen.html("-" + $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedGiftCard))
                                    $(t).attr("checked", false);
                                    that.alert(data)
                                }
                            }
                        });
                    } else {
                        this.ajax({
                            url: '/newshopping/CancelGiftCard',
                            data: {},
                            success: function (data) {
                                if (data.status == 1) {
                                    BENLAI.Model.OrderModels = data.data;
                                    $(t).parent().next().next().hide();
                                    $("#TxtUseGiftCard").val(0);
                                    wen.html("-" + $.BENLAI.toPrice(0))
                                    $("#TotalGiftCardPay").html('');
                                    that.ChangeSBG.call(that, t);
                                } else {
                                    that.alert(data)
                                }
                            }
                        });
                    }
                },
                ChangeSBG: function (t, event) {
                    $("#CanScore").html(BENLAI.Model.OrderModels.CanUseJiFen);
                    $("#CanBalance").html(BENLAI.Model.OrderModels.CanUseYuE);
                    $("#CanGiftCard").html(BENLAI.Model.OrderModels.CanUseGiftCard);
                    $("#TotalNeedPay").html($.BENLAI.toPrice(BENLAI.Model.OrderModels.TotalNeedPay));
                    if (BENLAI.Model.OrderModels.TotalNeedPay > 0) {
                        $("#invoiceUl input[name='invoiceType']").removeAttr("disabled");
                    } else {
                        $("#invoiceUl input[name='invoiceType']").first().click();
                        $("#invoice_title").hide();
                        $("#invoice_paper").hide();
                        $("#invoiceUl input[name='invoiceType']").attr("disabled", "disabled");
                    }
                },
                ChongGiftCard: function (t, event) {
                    var that = this;
                    //var id = $.trim($("#GiftCardId").val());
                    //if (id.length <= 0) { alert("请输入礼金卡卡号！"); return false; }
                    var pwd = $.trim($("#GiftCardPwd").val());
                    if (pwd.length <= 0) {
                        alert("请输入礼金卡密码！");
                        return false;
                    }
                    this.ajax({
                        url: '/newshopping/ChongGiftCard',
                        data: { CardPwd: pwd },
                        success: function (data) {
                            if (data.status == 1) {
                                BENLAI.Model.OrderModels = data.data;
                                $("#GiftCardId").val('');
                                $("#GiftCardPwd").val('');
                                $('#TotalCanGiftCard').html(BENLAI.Model.OrderModels.TotalCanUseGiftCard);
                                that.ChangeSBG.call(that, t);
                                $("#ChongCard").hide();
                                if (BENLAI.Model.OrderModels.IsUseGiftCard == 1) {
                                    $("#CBUseGiftCard").attr("checked", true);
                                    $("#CBUseGiftCard").parent().next().next().show();
                                    $("#TxtUseGiftCard").val(BENLAI.Model.OrderModels.UsedGiftCard);
                                    $("#CBUseGiftCard")
                                        .parent()
                                        .next()
                                        .next()
                                        .find(".payment_word02")
                                        .html("-" + $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedGiftCard))
                                    $("#TotalGiftCardPay")
                                        .html("- 账户礼金卡支付<b>" +
                                            $.BENLAI.toPrice(BENLAI.Model.OrderModels.UsedGiftCard) +
                                            "</b>元");
                                }
                                $.App.trigger("position:submit");
                            }
                            that.alert(data)
                        }
                    });
                },
                CancelChongGiftCard: function (t, event) {
                    $("#ChongCard").hide();
                },
                ZiNum: function (t, event) {
                    var c = $(t).val();
                    c = c.trim();
                    // var reg = /^[A-Za-z0-9]+$/; 
                    var reg = /^[\u4E00-\u9FA5a-zA-Z0-9]+$/;
                    if (!reg.test(c)) {
                        $(t).val('');
                        return false;
                    } else {
                        $(t).val(c);
                        return true;
                    }
                },
                NumXiaoYan: function (t, event) {
                    var intreg = /^\d+$/;
                    var sSum = $(t).val();
                    if (!intreg.test(sSum)) {
                        $(t).val('');
                        return false;
                    }
                },
                CheckCoupon: function (t, event) {
                    var CouponCode = $(t).attr("data-id");
                    BENLAI.Model.OrderModels.NowCheckCode = CouponCode;
                    this.UseCoupon();
                },
                PutUseCoupon: function (t, event) {
                    if (isInBlacklist == "1") {
                        alert("您无法绑券，请联系客服");
                        return false;
                    }
                    if ($("#ConponCodeTxt").val().length > 0) {
                        var CouponCode = $("#ConponCodeTxt").val();
                        BENLAI.Model.OrderModels.NowCheckCode = CouponCode;
                        $("#ConponCodeTxt").val('');
                        this.UseCoupon();
                    } else {
                        alert("请输入优惠券密码后添加！");
                        return false;
                    }
                },
                UseCoupon: function () {
                    var that = this;
                    CouponCode = BENLAI.Model.OrderModels.NowCheckCode;
                    this.ajax({
                        url: '/NewShopping/UseCoupon',
                        data: { CouponCode: CouponCode },
                        success: function (data) {

                            if (data.status == 1) {
                                BENLAI.Model.OrderModels = data.data;
                                if (CouponCode.length > 0) {
                                    BENLAI.Model.OrderTemp.CouponShow = true;
                                    BENLAI.Model.OrderModels.CheckCode = CouponCode;
                                }
                                $.App.trigger('bind:order');
                                if (!data.msg.IsNullOrEmpty())
                                    that.alert(data);
                            } else if (data.status == 2) {
                                ShowBack();
                                that.tmpl({
                                    dom: $("#telphontTlist"),
                                    v: BENLAI.Model.OrderTemp.CellPhoneList,
                                    datas: CouponCode
                                });
                                $("#TiShiErr").hide();
                                $("#CellTelPhoneT").show();
                            } else {
                                that.alert(data);
                                if (BENLAI.Model.OrderModels.CheckCode) {
                                    $('[data-id="' + BENLAI.Model.OrderModels.CheckCode + '"][type="radio"]')
                                        .attr("checked", true);
                                    $('[data-id="' + BENLAI.Model.OrderModels.NowCheckCode + '"][type="radio"]')
                                        .attr("checked", false);
                                } else {
                                    $('[data-id="' + BENLAI.Model.OrderModels.NowCheckCode + '"][type="radio"]').attr("checked", false);
                                }
                            }
                        }
                    });
                },
                SelectPageNum: function (t, event) {
                    var Pagenum = $(t).attr("data-num");
                    var OldNum = $(t).parent().find(".current").html();
                    if ($(t).attr("class") == "disabledl02" ||
                        $(t).attr("class") == "disabledr02" ||
                        $(t).attr("class") == "dian") return false;
                    if (Pagenum < 1) Pagenum = 1;
                    BENLAI.Shop.Orders.FenPage(Pagenum, OldNum);
                },
                GoToPageNum: function (t, event) {
                    var PageNum = Number($("#pageTxt").val());
                    var pgaeTotalNum = parseInt((BENLAI.Model.OrderModels.CustCoupon.length - 1) / 5) + 1;
                    var OldNum = Number($("#CouponPage").find(".current").html());
                    if (PageNum <= 0) PageNum = 1;
                    if (PageNum > pgaeTotalNum) {
                        PageNum = OldNum;
                        $("#pageTxt").val(PageNum);
                    }
                    if (PageNum == OldNum) return false;
                    BENLAI.Shop.Orders.FenPage(PageNum, OldNum);
                },
                CheckNum: function (t, event) {
                    validateCount.call($(t))
                },
                UseScoreChange: function (t, event) {
                    var intreg = /^\d+$/;
                    var sSum = $(t).val();
                    if (!intreg.test(sSum)) {
                        //var c = sSum.substring(0,sSum.length - 1);
                        //if (c.length <= 0) {
                        //    c = 0;
                        //}
                        $(t).val(BENLAI.Model.OrderModels.MustUseJiFen);
                        return false;
                    }
                    $(t).parent().siblings(".payment_word02").html("-" + $.BENLAI.toPrice(Number($(t).val()) / 10));
                },
                UseBalanceChange: function (t, event) {
                    var intreg = /(^\d+$)|(^\d+\.\d{1,1}$)|(^\d+\.$)/;
                    var sSum = $(t).val();
                    if (!intreg.test(sSum)) {
                        $(t).val("0");
                        return false;
                    }
                    $(t).parent().siblings(".payment_word02").html("-" + $.BENLAI.toPrice($(t).val()));
                },
                UseGiftCardChange: function (t, event) {
                    var intreg = /(^\d+$)|(^\d+\.\d{1,1}$)|(^\d+\.$)/;
                    var sSum = $(t).val();
                    if (!intreg.test(sSum)) {
                        $(t).val("0");
                        return false;
                    }
                    $(t).parent().siblings(".payment_word02").html("-" + $.BENLAI.toPrice($(t).val()));
                },
                selectPayType: function (t, event) {
                    $("#PayBankType").find("dd").removeClass("bank_bg");
                    $("[name=PayType]:checked").parent().parent().addClass("bank_bg");
                    BENLAI.Model.OrderTemp.PayType = $("[name=PayType]:checked").val();
                },
                ShowChongCard: function (t, event) {
                    $("#ChongCard").show();
                    $.App.trigger("position:submit");
                },
                ShowCoupon: function (t, event) {
                    if (isInBlacklist == "1") {
                        alert("您无法绑券，请联系客服");
                        event.preventDefault();
                        return false;
                    }
                    BENLAI.Model.OrderTemp.CouponShow = $(t).attr("checked");
                    if (BENLAI.Model.OrderTemp.CouponShow) {
                        if (BENLAI.Model.OrderModels.CustCoupon.length <= 0) {
                            BENLAI.Model.OrderTemp.CouponShow = false;
                            $(t).attr("checked", false);
                            alert("您没有优惠券，请添加绑定后再使用！");
                            return false;
                        }
                        $('[data-type="CouponShow"]').show();
                        $.App.trigger("position:submit");
                        var CouponCode = "";
                        $(BENLAI.Model.OrderModels.CustCoupon)
                            .each(function (k, v) {
                                if (v.IsCellPhoneCheck != 1) {
                                    CouponCode = v.CouponCode;
                                    $('[data-id="' +
                                            v
                                            .CouponCode +
                                            '"][type="radio"][name="CouponList"]')
                                        .attr("checked", true);
                                    return false;
                                }
                            });
                        BENLAI.Model.OrderModels.NowCheckCode = CouponCode;
                    } else {
                        $('[data-type="CouponShow"]').hide();
                        $.App.trigger("position:submit");
                        $('[type="radio"][name="CouponList"]').attr("checked", false);
                        BENLAI.Model.OrderModels.NowCheckCode = "";
                    }
                    this.UseCoupon();
                },
                CellPhoneOk: function (t, event) {
                    var phone = $("#YanZhengPhone").val();
                    var c = this.regExp.cellPhone;
                    var that = this;
                    if (!c.test(phone)) {
                        $("#TiShiErr").html("请输入正确的手机号码！");
                        $("#TiShiErr").show();
                        return false;
                    }
                    var code = $("#YanZhengCode").val();
                    var couponcode = { code: BENLAI.Model.OrderModels.NowCheckCode, error: "" };
                    this.ajax({
                        url: '/newshopping/CheckPhoneYanZhengMa',
                        data: { phone: phone, code: code },
                        success: function (data) {
                            if (data.status == 1) {
                                BENLAI.Model.OrderModels = data.data;
                                BENLAI.Model.OrderTemp.CouponShow = true;
                                HideBack();
                                $.App.trigger('bind:order');
                            } else {
                                couponcode.error = data.msg;
                                that.tmpl({
                                    dom: $("#telphontTlist"),
                                    v: BENLAI.Model.OrderTemp.CellPhoneError,
                                    datas: couponcode
                                });
                            }
                        }
                    });
                },
                SendSMS: function (t, event) {
                    var c = $(t).attr("IsVild");
                    var that = this;
                    if (c == 1) {
                        $("#TiShiErr").hide();
                        var phone = $("#YanZhengPhone").val();
                        var c = this.regExp.cellPhone;
                        if (!c.test(phone)) {
                            $("#TiShiErr").html("请输入正确的手机号码！");
                            $("#TiShiErr").show();
                            return false;
                        }
                        $(t).attr("IsVild", 2);
                        this.YanZhengMaRunTime();
                        this.ajax({
                            url: '/newshopping/GetPhoneYanZheng',
                            data: { phone: phone },
                            success: function (data) {
                                if (data.status == 1) {

                                } else {
                                    $("#TiShiErr").html(data.msg);
                                    $("#TiShiErr").show();
                                }
                            }
                        });
                    }
                },
                YanZhengMaRunTime: function () {
                    $("#YanZhengMa").html('');
                    var now = new Date();
                    var date = new Date(now.getTime() + 60000);
                    $.BENLAI.countDown({
                        dom: $('#YanZhengMa'),
                        date: date,
                        temp: '{second}秒后重新获取',
                        callback: function () {
                            $("#YanZhengMa").attr("IsVild", 1);
                            $("#YanZhengMa").html('重新获取验证码');
                        }
                    });
                },
                CancelPhone: function (t, event) {
                    BENLAI.Model.OrderTemp.CouponShow = false;
                    $(t).attr("checked", false)
                    $('[data-type="CouponShow"]').hide();
                    $.App.trigger("position:submit");
                    BENLAI.Model.OrderModels.NowCheckCode = "";
                    $("#CellTelPhoneT").hide();
                    HideBack();
                    this.UseCoupon();
                }
            })
    },
    FenPage: function (num, oldnum) {
        var pgaeTotalNum = parseInt((BENLAI.Model.OrderModels.CustCoupon.length - 1) / 5) + 1;
        var pnum = Number(num);
        var p1 = pnum - 2;
        if (p1 <= 1) p1 = -1;
        var p2 = pnum - 1;
        if (p2 <= 1) p2 = -1;
        var p3 = pnum + 1;
        if (p3 >= pgaeTotalNum) p3 = -1;
        var p4 = pnum + 2;
        if (p4 >= pgaeTotalNum) p4 = -1;
        var pagefen = "";
        if (pnum > 1) {
            pagefen += "<a class='disabledl' data-num='" + (p2 > 0 ? p2 : 1) + "' href='javascript:void(0)'>上一页</a>";
        } else {
            pagefen += "<a class='disabledl02' data-num='0' href='javascript:void(0)'>上一页</a>";
        }
        if (pnum == 1) {
            pagefen += "<span class='current'>1</span>";
        } else {
            pagefen += "<a href='javascript:void(0)' data-num='1'>1</a>";
        }
        if (p1 > 2) {
            pagefen += "<a class='dian'>...</a>";
        }
        if (p1 > 0) {
            pagefen += "<a href='javascript:void(0)' data-num='" + p1 + "'>" + p1 + "</a>";
        }
        if (p2 > 0) {
            pagefen += "<a href='javascript:void(0)' data-num='" + p2 + "'>" + p2 + "</a>";
        }
        if (pnum != 1 && pnum != pgaeTotalNum) {
            pagefen += "<span class='current'>" + pnum + "</span>";
        }
        if (p3 > 0) {
            pagefen += "<a href='javascript:void(0)' data-num='" + p3 + "'>" + p3 + "</a>";
        }
        if (p4 > 0) {
            pagefen += "<a href='javascript:void(0)' data-num='" + p4 + "'>" + p4 + "</a>";
        }
        if (p4 > pgaeTotalNum) {
            pagefen += "<a class='dian'>...</a>";
        }
        if (pnum == pgaeTotalNum) {
            pagefen += "<span class='current'>" + pgaeTotalNum + "</span>";
        } else {
            pagefen += "<a href='javascript:void(0)' data-num='" + pgaeTotalNum + "'>" + pgaeTotalNum + "</a>";
        }
        if (pnum < pgaeTotalNum) {
            pagefen += "<a class='disabledr' data-num='" +
                (p3 > 0 ? p3 : pgaeTotalNum) +
                "' href='javascript:void(0)'>下一页</a>";
        } else {
            pagefen += "<a class='disabledr02' data-num='0' href='javascript:void(0)'>下一页</a>";
        }
        $("#CouponPage").html(pagefen);
        $("#pageTxt").val(pnum);
        $("[data-couponfenid='" + oldnum + "']").hide();
        $("[data-couponfenid='" + pnum + "']").show();
    },
    Piao: function () {
        $('#PiaoView')
            .CreateController({
                events: {

                }
            })
    },
    ProductList: function () {
        $('#PListView')
            .CreateController({
                events: {
                    '.com_package a click': 'PListDetailExpandAndClose',
                    '[name=printmoney] click': 'selectPrint'
                },
                PListDetailExpandAndClose: function (t, event) {
                    var src = $(t).find("img").attr("src");
                    var dl = $(t).parent().parent().parent();
                    if (src.indexOf("ico02") != -1) {
                        dl.find(".com_print").show();
                        dl.find(".com_list").show();
                        $(t).find("img").attr("src", src.replace("ico02", "ico03"));
                    } else {
                        dl.find(".com_print").hide();
                        dl.find(".com_list").hide();
                        $(t).find("img").attr("src", src.replace("ico03", "ico02"));
                    }
                },
                selectPrint: function (t, event) {
                    BENLAI.Model.OrderTemp.Print = $("[name=printmoney]:checked").val();
                }
            })
    }
};

BENLAI.Model.OrderTemp = {};

function getArea(depth, areaSysNo, Netwide, Index) {
    var websiteSysNo = $("#websiteSysNo").val();
    var deliverySysNo = $("#deliverySysNo").val();
    if (!areaSysNo) {
        areaSysNo = deliverySysNo;
        depth = 1;
    }
    if (BENLAI.Model.OrderTemp.Netwide && BENLAI.Model.OrderTemp.GIndex) {
        Netwide = BENLAI.Model.OrderTemp.Netwide;
        Index = BENLAI.Model.OrderTemp.GIndex;
    }
    var URL = "/city/area?depth=" + depth + "&areaSysNo=" + areaSysNo + "&WebSiteSysNo=" + websiteSysNo;
    if (Netwide == 1) {
        URL = "/city/garea?depth=" +
            depth +
            "&areaSysNo=" +
            areaSysNo +
            "&WebSiteSysNo=" +
            websiteSysNo +
            "&fix=0_" +
            Index;
    }
    $.ajax({
        type: 'POST',
        url: URL,
        success: function (rs) {
            if (AjaxValidate(rs)) {
                rs.html = rs.html.replace("class='province'", 'class="village"');
                rs.html = rs.html.replace("class='city'", 'class="village"');
                $('#area').html(rs.html);
            } else {
                alert("加载地区信息失败，请刷新页面重试");
                $('#area').html("<font color='red'>加载地区信息失败，请刷新页面重试</font>");
            }
        },
        error: function () {
            alert("加载地区信息失败，请刷新页面重试");
            $('#area').html("<font color='red'>加载地区信息失败，请刷新页面重试</font>");
        }
    });
}

$(function () {
    try {
        var sitem = $('[data-type="sendtime"]').attr('data-shipid');

        $('[data-id="pfdrd"]').html($('[data-type="sendtimeselect"][data-shipid="' + sitem + '"]').attr("data-remark"));
    } catch (e) {
    }
});

function AreaIsEmpty() { }